package com.gaohc.framework.web.service;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gaohc.common.config.mybatisplus.AES;
import com.gaohc.common.constant.Constants;
import com.gaohc.common.core.domain.entity.SysUser;
import com.gaohc.common.core.redis.RedisUtil;
import com.gaohc.common.exception.BusinessException;
import com.gaohc.common.utils.DateUtils;
import com.gaohc.common.utils.ServletUtils;
import com.gaohc.common.utils.StringUtils;
import com.gaohc.common.utils.ip.IpUtils;
import com.gaohc.framework.manager.AsyncManager;
import com.gaohc.framework.manager.factory.AsyncFactory;
import com.gaohc.system.sysconfig.ISysConfigService;
import com.gaohc.system.sysuser.ISysUserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ISysUserService userService;
    @Resource
    private ISysConfigService configService;
    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCaptcha(username, code, uuid);
        }
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(SysUser::getUserName, username).last("limit 1");
        // 验证用户名密码是否正确
        SysUser sysUser = userService.getOne(sysUserLambdaQueryWrapper);
        if (StringUtils.isNull(sysUser)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "用户不存在"));
            throw new BusinessException("用户不存在");
        }
        if (!sysUser.getPassword().equals(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "密码输入错误"));
            throw new BusinessException("密码输入错误");
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功"));
        redisUtil.set(Constants.LOGIN_TOKEN_KEY + sysUser.getUserId(), sysUser);
        StpUtil.login(sysUser.getUserId());
        recordLoginInfo(sysUser.getUserId());
        // 获取token
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return tokenInfo.getTokenValue();
    }

    /**
     * 校验验证码
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        Object captcha = redisUtil.get(verifyKey);
        redisUtil.del(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "验证码已失效"));
            throw new BusinessException("验证码已失效");
        }
        if (!code.equalsIgnoreCase(captcha.toString()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "验证码错误"));
            throw new BusinessException("验证码错误");
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public static void main(String[] args) {
        String encrypt = AES.encrypt("0192023a7bbd73250516f069df18b500");
        System.out.println(encrypt);
    }

}
